package com.xunmall.base.interceptor.lock;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class RedisRequestLockInterceptor extends AbstractRequestLockInterceptor {

    @Autowired(required = false)
    private RedissonClient redissonClient;

    @Override
    protected Lock getLock(String key, long expirationTime) {
        RLock lock = redissonClient.getFairLock(key);
        lock.expire(expirationTime, TimeUnit.MILLISECONDS);
        return lock;
    }

    @Override
    protected boolean tryLock(long waitTime, Lock lock) throws InterruptedException {
        return ((RLock)lock).tryLock(waitTime, TimeUnit.MILLISECONDS);
    }

    @Override
    protected void unlock(Lock lock) {
        try {
            lock.unlock();
        } catch (Exception e) {
            log.warn("unlock error : " + e.getMessage());
        }
    }
}